import React, { useState, useEffect } from 'react';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import {
  ProFormText,
  ProFormTextArea,
  ProFormDatePicker,
  ProFormSelect
} from '@ant-design/pro-form';
import { Form, Modal, Row, Col, Upload, Tag, message } from 'antd';
import { useIntl, FormattedMessage } from 'umi';
export type FormValueType = {} & Partial<TableListItem>;

export type UpdateFormProps = {
  onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  onSubmit: (values: FormValueType) => Promise<void>;
  updateModalVisible: boolean;
  values: Partial<TableListItem>;
};

function beforeUpload(file: any) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
}


function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}


const UpdateForm: React.FC<UpdateFormProps> = (props) => {
  const [form] = Form.useForm();
  //上传
  const [loading, setLoading] = useState<boolean>(false);
  const [imageUrl, setImageUrl] = useState<string>();
  const [fileIds, setFileIds] = useState<string>();

  useEffect(() => {
    form.resetFields();
    form.setFieldsValue({
      id: props.values.id,
      login_name: props.values.login_name,
      name: props.values.name,
      login_password: '',
      confirm_password: '',
      sex: props.values.sex,
      phone: props.values.phone,
      email: props.values.email,
      birth_date: props.values.birth_date,
      motto: props.values.motto,
      order_by: props.values.order_by,
      live_address: props.values.live_address,
      birth_address: props.values.birth_address,
      remark: props.values.remark,
      status: props.values.status,
      fileIds: props.values.fileIds,
    })
  });
  // setInitialValues(props.values)
  // useEffect(() => {
  //   console.log('---------------')
  //   setInitValues(props.values)
  //   console.log(initValues)
  // });
  const intl = useIntl();
  let index = 0;
  const handleOk = () => {
    form.submit();
    if (index > 0) {
      props.onCancel()
    }
    index++;
  };
  const handleCancel = () => {
    props.onCancel()
  }
  const handleFinish = (values: Record<string, any>) => {

    props.onSubmit({...values,old_login_name:props.values.login_name} as FormValueType);
  };


  const uploadImage = async (file: any) => {
    setLoading(true);
    const formData = new FormData();
    formData.append("file", file.file);
    await upload(formData).then(res => {
      setLoading(false);
      setImageUrl(res.data.show_file_path)
      setFileIds(res.data.id)
    })
  }

  const handleChange = async (info: any) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, (imageUrl: any) => {
        setLoading(true);
        setImageUrl(imageUrl);
      });
    }
  }

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传</div>
    </div>
  );

  const checkPassword = (rule: any, value: string) => {
    let login_password = form.getFieldValue("login_password");
    if (value == login_password) { //校验条件自定义
      return Promise.resolve();
    }
    return Promise.reject('两次密码输入不一致');
  };

  // setInitValues(props.values);
  return (
    <Modal
      width={900}
      title={intl.formatMessage({
        id: '编辑用户',
        defaultMessage: '编辑用户',
      })}
      visible={props.updateModalVisible}
      destroyOnClose
      onOk={handleOk} onCancel={handleCancel}
    // onFinish={props.onSubmit}
    // onVisibleChange={handleOk}
    // initialValues={props.values}
    >
      <Form
        form={form}
        onFinish={handleFinish}
        // initialValues={props.values}
        initialValues={{

        }}
      >
        <Row gutter={[16, 16]}>
          <Col span={12} order={2}>
            <ProFormText
              label={intl.formatMessage({
                id: '登录账号',
                defaultMessage: '登录账号',
              })}
              rules={[
                {
                  required: true,
                  message: "登录账号不可为空。",
                },
              ]}
              width="xl"
              name="login_name"
              placeholder="请输入登录账号"
            />
          </Col>
          <Col span={12} order={1}>
            <ProFormText
              label={intl.formatMessage({
                id: '姓名',
                defaultMessage: '姓名',
              })}
              rules={[
                {
                  required: true,
                  message: "姓名不可为空。",
                },
              ]}
              width="xl"
              name="name"
              placeholder="请输入姓名"
            />
          </Col>
        </Row>
        <Row gutter={[16, 16]}>
          <Col span={12} order={2}>
            <ProFormSelect
              width="xl"
              options={[
                {
                  value: "1",
                  label: "男",
                },
                {
                  value: "2",
                  label: "女",
                }
              ]}
              placeholder="请选择性别"
              name="sex"
              label="性别"
            />
          </Col>
          <Col span={12} order={2}>
            <ProFormText
              label={intl.formatMessage({
                id: '手机号',
                defaultMessage: '手机号',
              })}
              rules={[
                {
                  required: true,
                  message: '请输入手机号',
                },
                {
                  max: 11,
                  message: '最长11位!',
                },
                {
                  pattern: /^1[3|4|5|6|7|8|9]\d{9}$/,
                  message: '请输入正确的手机号',
                }
              ]}
              width="xl"
              name="phone"
              placeholder="请输入手机号"
            />
          </Col>
        </Row>
        <Row gutter={[16, 16]}>
          <Col span={12} order={2}>
            <ProFormText
              label={intl.formatMessage({
                id: '邮箱',
                defaultMessage: '邮箱',
              })}
              width="xl"
              name="email"
              placeholder="请输入邮箱"
              rules={[
                {
                  type: 'email',
                  message: '请输入正确邮箱',
                  // pattern: /^[0-9]+$/,
                }
              ]}
            />
          </Col>
          <Col span={12} order={2}>
            <ProFormDatePicker width="xl" name="birth_date" label="出生日期" placeholder="请输入出生日期" />
          </Col>
        </Row>
        <Row gutter={[16, 16]}>
          <Col span={12} order={2}>
            <ProFormText
              label={intl.formatMessage({
                id: '座右铭',
                defaultMessage: '座右铭',
              })}
              width="xl"
              name="motto"
              placeholder="请输入座右铭"
            />
          </Col>
          <Col span={12} order={2}>
            <ProFormText
              label={intl.formatMessage({
                id: '排序号',
                defaultMessage: '排序号',
              })}
              width="xl"
              name="order_by"
              placeholder="请输入排序号"
              rules={
                [
                  {
                    pattern: new RegExp(/^[1-9]\d*$/, "g"),
                    message: '只能输入数字'
                  }
                ]
              }
            />
          </Col>
        </Row>
        <Row gutter={[16, 16]}>
          <Col span={12} order={2}>
            <ProFormText
              label={intl.formatMessage({
                id: '居住地址',
                defaultMessage: '居住地址',
              })}
              width="xl"
              name="live_address"
              placeholder="请输入居住地址"
            />
          </Col>
          <Col span={12} order={2}>
            <ProFormText
              label={intl.formatMessage({
                id: '出生地址',
                defaultMessage: '出生地址',
              })}
              width="xl"
              name="birth_address"
              placeholder="请输入出生地址"
            />
          </Col>
        </Row>
        {/* <Row gutter={[16, 16]}>
          <Col span={24} order={1}>
            <ProFormText
              label={intl.formatMessage({
                id: '职位',
                defaultMessage: '职位',
              })}
              width="xl"
              name="position"
              placeholder="请输入职位"
            />
          </Col>
        </Row> */}
        <Row gutter={[16, 16]}>
          <Col span={24} order={1}>
            <Upload
              name="avatar"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              // action=""
              customRequest={uploadImage}
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
            </Upload>
          </Col>
        </Row>
        <Row gutter={[16, 16]}>
          <Col span={24} order={1}>
            <ProFormTextArea
              name="remark"
              label="备注"
              placeholder="请输入备注"
            />
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};

export default UpdateForm;
